import { ref } from 'vue'

import { debug } from './config'

/**
 * 消息打印
 * @param contents 消息内容
 * @param type 类型
 */
const log = (contents: any[], type: 'log' | 'error' | 'warn' | 'debug' = 'log') =>
  debug && console[type](...(Array.isArray(contents) ? contents : [contents]))

/**
 * 消息提示
 * @param title 消息内容
 * @param icon 图标
 * @param duration 持续时间
 */
const toast = (
  title: string,
  icon: 'none' | 'success' | 'error' | 'loading' = 'none',
  duration: number = 5000,
) => uni.showToast({ title, icon, duration })

const isLoading = ref(false)

/**
 * 是否显示加载
 * @param show 是否显示
 * @param title 提示
 */
const loading = (show: boolean) => (isLoading.value = show)
// const loading = (show: boolean, title: string = '') =>
//   show ? uni.showLoading({ title, mask: true }) : uni.hideLoading()

/**
 * 合成错误信息
 */
const makeErrMsg = (err: any, msg = '网络错误，请稍后再尝试') => {
  switch (typeof err) {
    case 'string':
      return err || msg

    case 'object':
      if (err.errMsg === 'request:fail') err.errMsg = ''

      const code = err.errCode || err.code || err.statusCode

      return (code ? `[${code}] ` : '') + (err.errMsg || err.message || msg)

    default:
      return msg
  }
}

export { log, toast, isLoading, loading, makeErrMsg }
